// pages/register/register.ts
Page({
  data: {
    name: '',
    password: '',
    genderList: ['男', '女'],
    genderIndex: 0,
    hobby: '',
    undergraduate: '',
    target: ''
  },

  onLoad() {},
  onReady() {},
  onShow() {},
  onHide() {},
  onUnload() {},
  onPullDownRefresh() {},
  onReachBottom() {},
  onShareAppMessage() {},

  onNameInput(e: WechatMiniprogram.Input) {
    this.setData({ name: e.detail.value })
  },
  onPasswordInput(e: WechatMiniprogram.Input) {
    this.setData({ password: e.detail.value })
  },
  onGenderChange(e: WechatMiniprogram.PickerChange) {
    this.setData({ genderIndex: Number(e.detail.value) })
  },
  onHobbyInput(e: WechatMiniprogram.Input) {
    this.setData({ hobby: e.detail.value })
  },
  onUndergraduateInput(e: WechatMiniprogram.Input) {
    this.setData({ undergraduate: e.detail.value })
  },
  onTargetInput(e: WechatMiniprogram.Input) {
    this.setData({ target: e.detail.value })
  },

  register() {
    if (!this.data.name || !this.data.password || !this.data.hobby || 
        !this.data.undergraduate || !this.data.target) {
      wx.showToast({
        title: '请填写完整信息',
        icon: 'none'
      })
      return
    }

    wx.request({
      url: 'http://localhost:8080/api/user/register',
      method: 'POST',
      data: {
        name: this.data.name,
        password: this.data.password,
        gender: this.data.genderList[this.data.genderIndex],
        hobby: this.data.hobby,
        undergraduate: this.data.undergraduate,
        target: this.data.target
      },
      success: (res: WechatMiniprogram.RequestSuccessCallbackResult) => {
        const response = res.data as { code: number; message: string }
        if (response.code === 200) {
          wx.showToast({
            title: '注册成功',
            icon: 'success'
          })
          wx.navigateTo({
            url: '/pages/login/login'
          })
        } else {
          wx.showToast({
            title: response.message,
            icon: 'none'
          })
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        })
      }
    })
  },

  toLogin() {
    wx.navigateTo({
      url: '/pages/login/login'
    })
  }
})